<template>
  <div class="common-wrapper">
    <div class="common-search">
      <a-form layout="inline">
        <a-form-item label="部门">
          <a-select v-model="search.department" style="width:150px;">
            <a-select-option v-for="item in departmentList" :key="item.pkey">
              {{ item.dep_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="工种">
          <a-select v-model="search.work_type" style="width:150px;">
            <a-select-option v-for="item in datadictionary" :key="item.data_value">
              {{ item.data_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="员工姓名">
          <a-input v-model="search.name" />
        </a-form-item>
        <a-form-item label="员工工号">
          <a-input v-model="search.person_idcard" />
        </a-form-item>
        <a-form-item label="时间范围">
          <a-range-picker @change="onChangeTime" />
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="getTableData(1)"> 搜索 </a-button>
      <a-button type="primary" style="margin-left: 15px" @click="exportWithdrawal" :loading="eloading"> 导出数据 </a-button>
      <a-button
        type="danger"
        style="background: #13c2c2; border-color: #13c2c2; margin-left: 15px"
        @click="openDialog()"
      >
        处理考勤
      </a-button>
    </div>
    <div class="common-main" ref="main">
      <a-table
        size="middle"
        :rowClassName="tableRowClass"
        :rowKey="(record) => record.code"
        :columns="columns"
        :scroll="{ x: 500, y: 600 }"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="name" slot-scope="text, record">
          <a-tooltip overlayClassName="draw_atooltip" @visibleChange="visibleChange($event, record)">
            <template slot="title">
              <a-table
                :columns="columns1"
                size="small"
                :loading="tipsLoading"
                :pagination="false"
                :rowKey="(record) => record.pkey"
                :data-source="inoutrecordList"
              >
                <template slot="comm_type" slot-scope="text, record">
                  <span :class="record.comm_type === '出' ? 'color_red' : 'color_green'">{{ record.comm_type }}</span>
                </template>
              </a-table>
            </template>
            <span>{{ record.name }}</span>
          </a-tooltip>
        </template>
        <template slot="work_type" slot-scope="text, record">
          <span>{{ workType(record.work_type) }}</span>
        </template>
        <template slot="first_card" slot-scope="text, record">
          <span v-if="record.first_card">{{ record.first_card.split(' ')[1] }}</span>
        </template>
        <template slot="last_card" slot-scope="text, record">
          <span v-if="record.last_card">{{ record.last_card.split(' ')[1] }}</span>
        </template>
        <template slot="go_out_state" slot-scope="text, record">
          <span>{{ record.go_out_state === 1 ? '超时' : '正常' }}</span>
        </template>
        <template slot="go_out_time" slot-scope="text">
          <span>{{ Math.floor(text) }}</span>
        </template>
        <template slot="attendance" slot-scope="text">
          <span>{{ Math.floor(text) }}</span>
        </template>
        <template slot="work_overtime" slot-scope="text">
          <span>{{ Math.floor(text) }}</span>
        </template>
        <template v-if="record.daily_shift_list[0]" slot="status1" slot-scope="text, record">
          <span>{{ record.daily_shift_list[0].status | statusFilter }}</span>
        </template>
        <template v-if="record.daily_shift_list[0]" slot="late1" slot-scope="text, record">
          <span>{{ Math.floor(record.daily_shift_list[0].late) }}</span>
        </template>
        <template v-if="record.daily_shift_list[0]" slot="early1" slot-scope="text, record">
          <span>{{ Math.floor(record.daily_shift_list[0].leave_early) }}</span>
        </template>
        <template v-if="record.daily_shift_list[0]" slot="arrive1" slot-scope="text, record">
          <span v-if="record.daily_shift_list[0].real_arrive">{{ record.daily_shift_list[0].real_arrive.split(' ')[1] }}</span>
        </template>
        <template v-if="record.daily_shift_list[0]" slot="back1" slot-scope="text, record">
          <span v-if="record.daily_shift_list[0].real_back">{{ record.daily_shift_list[0].real_back.split(' ')[1] }}</span>
        </template>
        <template v-if="record.daily_shift_list[1]" slot="status2" slot-scope="text, record">
          <span>{{ record.daily_shift_list[1].status | statusFilter }}</span>
        </template>
        <template v-if="record.daily_shift_list[1]" slot="late2" slot-scope="text, record">
          <span>{{ Math.floor(record.daily_shift_list[1].late) }}</span>
        </template>
        <template v-if="record.daily_shift_list[1]" slot="early2" slot-scope="text, record">
          <span>{{ Math.floor(record.daily_shift_list[1].leave_early) }}</span>
        </template>
        <template v-if="record.daily_shift_list[1]" slot="arrive2" slot-scope="text, record">
          <span v-if="record.daily_shift_list[1].real_arrive">{{ record.daily_shift_list[1].real_arrive.split(' ')[1] }}</span>
        </template>
        <template v-if="record.daily_shift_list[1]" slot="back2" slot-scope="text, record">
          <span v-if="record.daily_shift_list[1].real_back">{{ record.daily_shift_list[1].real_back.split(' ')[1] }}</span>
        </template>
        <template v-if="record.daily_shift_list[2]" slot="status3" slot-scope="text, record">
          <span>{{ record.daily_shift_list[2].status | statusFilter }}</span>
        </template>
        <template v-if="record.daily_shift_list[2]" slot="late3" slot-scope="text, record">
          <span>{{ Math.floor(record.daily_shift_list[2].late) }}</span>
        </template>
        <template v-if="record.daily_shift_list[2]" slot="early3" slot-scope="text, record">
          <span>{{ Math.floor(record.daily_shift_list[2].leave_early) }}</span>
        </template>
        <template v-if="record.daily_shift_list[2]" slot="arrive3" slot-scope="text, record">
          <span v-if="record.daily_shift_list[2].real_arrive">{{ record.daily_shift_list[2].real_arrive.split(' ')[1] }}</span>
        </template>
        <template v-if="record.daily_shift_list[2]" slot="back3" slot-scope="text, record">
          <span v-if="record.daily_shift_list[2].real_back">{{ record.daily_shift_list[2].real_back.split(' ')[1] }}</span>
        </template>
        <template slot="date" slot-scope="text, record">
          <span>{{ record.date.split(' ')[0] }}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button style="padding: 0" type="link" @click="openChangePlan(record)">修改班次</a-button>
        </template>
      </a-table>
    </div>
    <!-- modal -->
    <a-modal title="处理考勤" :visible="visible" @cancel="handleCancel">
      <a-form-model ref="form" :model="form" :rules="rules">
        <a-form-model-item label="时间范围选择" :colon="false" prop="time">
          <a-range-picker v-model="form.time" :disabled-date="disabledDate" @change="onChange" style="width: 100%" />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="submitStaff" :loading="subLoading">确定</a-button>
      </template>
    </a-modal>
    <!-- 修改排班 -->
    <a-modal title="修改排班" :visible="visiblePlan" @cancel="handleCancelPlan">
      <a-form-model ref="formPlan" :model="formPlan">
        <a-form-model-item label="选择班次" :colon="false">
          <a-select v-model="formPlan.class_key" @change="handleSelect">
            <a-select-option v-for="(item, key) of planList" :key="key" :value="key">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="handleCancelPlan">取消</a-button>
        <a-button type="primary" @click="submitPlan">确定</a-button>
      </template>
    </a-modal>

    <!-- 提取数据 -->
    <a-modal title="提取" :visible="visiblePull" @cancel="visiblePull=false">
      <a-form :form="formPull">
        <a-form-item label="时间范围选择" :colon="false">
          <a-range-picker :show-time="{
                            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                          }"
                          format="YYYY-MM-DD HH:mm:ss"
                          :disabled-date="disabledDate"
                          v-decorator="[
                            'time',
                            { rules: [{ required: true, message: '请选择时间范围' }],
                              initialValue: [] },
                          ]"
                          style="width: 100%" />
        </a-form-item>
        <a-form-item label="设备" :colon="false">
          <a-select
            v-decorator="[
              'machine_id',
              { rules: [{ required: true, message: '请选择设备' }]},
            ]"
            placeholder="请选择设备"
          >
            <a-select-option v-for="(item, index) of deviceList" :key="index" :value="Number(index)">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="visiblePull=false">取消</a-button>
        <a-button type="primary" @click="submitPull" :loading="pullLoading">确定</a-button>
      </template>
    </a-modal>

    <!-- modal -->
    <a-modal title="员工进出名单导出" :visible="visible1" @cancel="visible1=false">
      <a-form :form="formExport">
        <a-form-item label="时间范围选择" :colon="false">
          <a-range-picker :show-time="{
                            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                          }"
                          format="YYYY-MM-DD HH:mm:ss"
                          :disabled-date="disabledDate"
                          v-decorator="[
                            'time',
                            { rules: [{ required: true, message: '请选择时间范围' }],
                              initialValue: [] },
                          ]"
                          style="width: 100%" />
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="visible1=false">取消</a-button>
        <a-button type="primary" @click="submitExport" :loading="loadingExport">导出</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { exportDailyStatistics, inoutrecord, pullRecord, getControlSelector, exportInoutRecord } from '@/api/attendance'
import { getClassSelect, changePlan, getDepartmentList, getDatadictionary, getSpecialattendance, setSpecialattendance } from '@/api/plan'
import moment from 'moment'
export default {
  data () {
    const columns = [
      {
        title: '部门',
        dataIndex: 'department',
        align: 'center',
        width: 80
      },
      {
        title: '姓名',
        dataIndex: 'name',
        align: 'center',
        scopedSlots: { customRender: 'name' },
        width: 60
      },
    //   {
    //     title: '所上班制',
    //     dataIndex: 'system_work',
    //     align: 'center',
    //     width: 80
    //   },
      {
        title: '日期',
        scopedSlots: { customRender: 'date' },
        align: 'center',
        width: 90
      },
      {
        title: '工种',
        dataIndex: 'work_type',
        scopedSlots: { customRender: 'work_type' },
        align: 'center',
        width: 80
      },
      {
        title: '工号',
        dataIndex: 'person_idcard',
        align: 'center',
        width: 90
      },
      {
        title: '首次打卡',
        scopedSlots: { customRender: 'first_card' },
        align: 'center',
        width: 75
      },
      {
        title: '下班打卡',
        scopedSlots: { customRender: 'last_card' },
        align: 'center',
        width: 75
      },
      {
        title: '外出状态',
        scopedSlots: { customRender: 'go_out_state' },
        align: 'center',
        width: 50
      },
       {
        title: '外出时长',
        dataIndex: 'go_out_time',
        scopedSlots: { customRender: 'go_out_time' },
        align: 'center',
        width: 55
      },
    //   {
    //     title: '出勤分钟',
    //     dataIndex: 'attendance',
    //     scopedSlots: { customRender: 'attendance' },
    //     align: 'center',
    //     width: 55
    //   },
    //   {
    //     title: '平时加班',
    //     dataIndex: 'work_overtime',
    //     scopedSlots: { customRender: 'work_overtime' },
    //     align: 'center',
    //     width: 55
    //   },
      {
        title: '段一状态',
        align: 'center',
        scopedSlots: { customRender: 'status1' },
        width: 55
      },
      {
        title: '段一迟到',
        align: 'center',
        scopedSlots: { customRender: 'late1' },
        width: 55
      },
      {
        title: '段一早退',
        align: 'center',
        scopedSlots: { customRender: 'early1' },
        width: 55
      },
      {
        title: '段一实到',
        align: 'center',
        scopedSlots: { customRender: 'arrive1' },
        width: 75
      },
      {
        title: '段一实退',
        align: 'center',
        scopedSlots: { customRender: 'back1' },
        width: 75
      },
      {
        title: '段二状态',
        align: 'center',
        scopedSlots: { customRender: 'status2' },
        width: 55
      },
      {
        title: '段二迟到',
        align: 'center',
        scopedSlots: { customRender: 'late2' },
        width: 55
      },
      {
        title: '段二早退',
        align: 'center',
        scopedSlots: { customRender: 'early2' },
        width: 55
      },
      {
        title: '段二实到',
        align: 'center',
        scopedSlots: { customRender: 'arrive2' },
        width: 75
      },
      {
        title: '段二实退',
        align: 'center',
        scopedSlots: { customRender: 'back2' },
        width: 75
      },
      {
        title: '段三状态',
        align: 'center',
        scopedSlots: { customRender: 'status3' },
        width: 55
      },
      {
        title: '段三迟到',
        align: 'center',
        scopedSlots: { customRender: 'late3' },
        width: 55
      },
      {
        title: '段三早退',
        align: 'center',
        scopedSlots: { customRender: 'early3' },
        width: 55
      },
      {
        title: '段三实到',
        align: 'center',
        scopedSlots: { customRender: 'arrive3' },
        width: 75
      },
      {
        title: '段三实退',
        align: 'center',
        scopedSlots: { customRender: 'back3' },
        width: 75
      }
    //   {
    //     title: '操作',
    //     width: 80,
    //     align: 'center',
    //     fixed: 'right',
    //     scopedSlots: { customRender: 'action' }
    //   }
    ]
    return {
      departmentList: [],
      search: {
        name: '',
        person_idcard: '',
        department: '',
        work_type: '',
        start_time: '',
        end_time: '',
        page_index: 1,
        page_size: 100
      },
      form: {
        time: null
      },
      columns,
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 100,
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: false,
        total: 0
      },
      loading: false,
      subLoading: false,
      eloading: false,
      visible: false,
      dataSource: [],
      rules: {
        time: [{ required: true, message: '请选择时间范围', trigger: 'change' }]
      },
      planList: [],
      datadictionary: [], // 工种列表
      visiblePlan: false,
      formPlan: {
        code: '',
        class_key: ''
      },
      inoutrecordList: [],
      columns1: [
        {
          title: '进出类型',
          scopedSlots: { customRender: 'comm_type' },
          dataIndex: 'comm_type',
          align: 'center'
        },
        {
          title: '进出时间',
          dataIndex: 'record_time',
          align: 'center'
        }
      ],
      tipsLoading: false,
      visiblePull: false,
      formPull: this.$form.createForm(this),
      pullLoading: false,
      deviceList: [{
        id: '1111',
        name: '192.168.1.109'
      }], // 设备列表
      visible1: false, // 打卡名单导出
      formExport: this.$form.createForm(this),
      loadingExport: false

    }
  },
  filters: {
    statusFilter (value) {
      let str = ''
      switch (value) {
        case 0:
          str = '正常'
          break
        case 1:
          str = '迟到'
          break
        case 2:
          str = '早退'
          break
        case 3:
          str = '迟到+早退'
          break
        case 4:
          str = '旷工'
          break
        case 8:
          str = '缺卡'
          break
        case 9:
          str = '迟到+缺卡'
          break
        case 10:
          str = '早退+缺卡'
          break
      }
      return str
    }
  },
  computed: {
    workType () {
      return function (value) {
        for (let index = 0; index < this.datadictionary.length; index++) {
          if (this.datadictionary[index].data_value === value) {
            return this.datadictionary[index].data_name
          }
        }
      }
    }
  },
  mounted () {
    this.resize()
    this.getPlanList()
    this.getDepartmentList()
    this.getDatadictionary()
    this.getDeviceList()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    moment,
    getDeviceList () {
      getControlSelector().then(res => {
        const { succeeded, data } = res
        if (succeeded) {
          this.deviceList = data
        }
      })
    },
    onPull () {
      this.visiblePull = true
    },
    // 提取考勤数据
    submitPull (e) {
      e.preventDefault()
      this.formPull.validateFields((err, values) => {
        console.log(values);
        if (!err) {
          this.pullLoading = true
          var params = Object.assign({}, values)
          params.start_time = moment(values.time[0]).format('YYYY-MM-DD HH:mm:ss')
          params.end_time = moment(values.time[1]).format('YYYY-MM-DD HH:mm:ss')
          delete params.time
          pullRecord(params).then(res => {
            const { succeeded, errors } = res
            if (succeeded) {
              this.formPull.resetFields()
              this.$message.success('操作成功！')
            } else {
              this.$message.error(errors)
            }
            this.pullLoading = false
          }).catch(() => {
            this.pullLoading = false
          })
        }
      })
    },
    disabledDate (current) {
      // 不可选未来时间
      return current && current > Date.now();
    },
    tableRowClass (record) {
      const str = String(record.daily_shift_list[0].status === 10 ? 5 : record.daily_shift_list[0].status) + String(record.daily_shift_list[1].status === 10 ? 5 : record.daily_shift_list[1].status) + String(record.daily_shift_list[2].status === 10 ? 5 : record.daily_shift_list[2].status)
      if (str.indexOf('4') >= 0) {
        return 'absenStyle'
      }
      if (str.indexOf('2' || '3' || '5') >= 0) {
        return 'earStyle'
      }
      if (str.indexOf('1' || '9') >= 0) {
        return 'lateStyle'
      }
      if (str.indexOf('8') >= 0) {
        return 'leakStyle'
      }
      return ''
    },
    async visibleChange (visible, item) {
      if (visible) {
        this.tipsLoading = true
        await this.getInoutrecord(item)
        this.tipsLoading = false
      } else {
        this.inoutrecordList = []
      }
    },
    // 获取进去记录
    async getInoutrecord (item) {
      const params = {
        end_time: item.date.split(' ')[0] + " 23:59:59",
        start_time: item.date.split(' ')[0] + " 00:00:00",
        id_card: item.person_idcard
      }
      const { data } = await inoutrecord(params)
      this.inoutrecordList = data.items
    },
    // 获取部门列表
    async getDepartmentList () {
      const { data } = await getDepartmentList()
      this.departmentList = data
      this.departmentList.unshift({
        dep_name: "全部部门",
        pkey: ''
      })
    },
    // 获取工种
    async getDatadictionary () {
      const { data } = await getDatadictionary({ data_type: 3 })
      this.datadictionary = data
      this.datadictionary.unshift({
        data_name: "全部工种",
        data_value: ''
      })
    },
    // 批量导出
    exportWithdrawal () {
      const params = { ...this.search }
      this.eloading = true
      if (params.work_type === '') {
        params.work_type = null;
      }
      if (params.end_time === '') {
        params.end_time = null;
      }
       if (params.start_time === '') {
        params.start_time = null;
      }
      params.department = params.department + ''
      exportDailyStatistics(params).then((res) => {
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const fileName = '特殊考勤日统计明细.xlsx'
        const edlink = document.createElement('a')
        edlink.download = fileName
        edlink.href = URL.createObjectURL(blob)
        document.body.appendChild(edlink)
        edlink.click()
        URL.revokeObjectURL(edlink.href) // 释放URL 对象
        document.body.removeChild(edlink)
        this.eloading = false
      })
    },

    // 导入打卡名单
    submitExport (e) {
      e.preventDefault()
      this.formExport.validateFields((err, values) => {
        console.log(values);
        if (!err) {
          this.loadingExport = true
          var params = Object.assign({}, values)
          params.start_time = moment(values.time[0]).format('YYYY-MM-DD HH:mm:ss')
          params.end_time = moment(values.time[1]).format('YYYY-MM-DD HH:mm:ss')
          delete params.time

           exportInoutRecord(params).then((res) => {
            const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
            const fileName = '员工进出名单.xlsx'
            const edlink = document.createElement('a')
            edlink.download = fileName
            edlink.href = URL.createObjectURL(blob)
            document.body.appendChild(edlink)
            edlink.click()
            URL.revokeObjectURL(edlink.href) // 释放URL 对象
            document.body.removeChild(edlink)
            this.loadingExport = false
            this.formExport.resetFields()
            this.visible1 = false
          })
        }
      })
    },
    async resize () {
      // this.getPageSize()
      await this.getTableData()
    },
    // 修改排班
    openChangePlan (item) {
      this.formPlan.code = item.code
      this.visiblePlan = true
    },
    handleCancelPlan () {
      this.formPlan.code = ''
      this.formPlan.class_key = ''
      this.$refs.formPlan.resetFields()
      this.visiblePlan = false
    },
    handleSelect (value) {
      this.formPlan.class_key = value
    },
    async submitPlan () {
      const { succeeded } = await changePlan(this.formPlan)
      if (succeeded) {
        this.resize()
        this.$message.success('修改成功，请重新处理考勤数据！')
      } else {
         this.$message.error('操作失败！')
      }
      this.formPlan.code = ''
      this.formPlan.class_key = ''
      this.visiblePlan = false
      this.$refs.formPlan.resetFields()
    },
    // 获取班次下拉框
    async getPlanList () {
      const { data } = await getClassSelect()
      this.planList = data
    },
    // end
    onChangeTime (date, dateString) {
      this.search.start_time = dateString[0]
      this.search.end_time = dateString[1]
    },
    openDialog () {
      this.visible = true
    },
    handleCancel () {
      this.visible = false
      this.$refs.form.resetFields()
    },
    submitStaff () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.subLoading = true
          const params = {}
          params.start_time = this.form.time[0]
          params.end_time = this.form.time[1]
          const { succeeded, errors } = await setSpecialattendance('process', params)
          if (succeeded) {
            this.$message.success('操作成功！')
            this.visible = false
            this.$refs.form.resetFields()
          } else {
            this.$message.error(errors)
          }
          this.subLoading = false
        } else {
          return false
        }
      })
    },
    onChange (date, dateString) {
      this.form.time = dateString
    },
    // 获取表格
    async getTableData (cur) {
      this.loading = true
      if (cur === 1) {
        this.search.page_index = cur
        this.pagination.current = cur
      } else {
        this.search.page_index = this.pagination.current
      }
      const { data } = await getSpecialattendance('getdailystatistical', this.search)
      this.dataSource = data.items
      this.pagination.total = data.totalCount
      this.loading = false
    },
    getPageSize () {
      const height = this.$refs.main.offsetHeight - 68 - 30
      const pageSize = Math.floor(height / 50)
      this.search.page_size = pageSize
      this.pagination.pageSize = pageSize
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.getTableData()
    }
  }
}
</script>

<style lang="less">
.common-wrapper {
  height: 100%;
  padding: 20px;
}
.common-search {
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #efefef;
}
.common-main {
  height: calc(100% - 50px);
  padding-top: 10px;
  .ant-table .ant-btn {
    height: 24px;
    line-height: 24px;
  }
}
// 迟到
.lateStyle {
  background: rgb(193, 68, 68);
}
// 早退
.earStyle {
  background: rgb(150, 128, 141);
}
// 旷工
.absenStyle {
  background: rgb(109, 76, 58);
}
// 缺卡
.leakStyle {
  background: rgb(50, 120, 117);
}
//控制主体颜色
.draw_atooltip .ant-tooltip-inner {
  color: #333 !important;
  background-color: #fff !important;
}
//控制三角形颜色
.draw_atooltip .ant-tooltip-arrow::before {
  background-color: #fff;
}
.color_red {
  color: red;
}
.color_green {
  color: green;
}
</style>
